package com.so206.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.so206.mapper.SystemCcConfigMapper;
import com.so206.mapper.SystemCcRecordMapper;
import com.so206.po.SystemCcConfig;
import com.so206.po.SystemCcRecord;
import com.so206.service.SystemCcService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class SystemCcServiceImpl implements SystemCcService {

    @Autowired
    private SystemCcConfigMapper ccConfigMapper;

    @Autowired
    private SystemCcRecordMapper recordMapper;

    @Override
    public SystemCcConfig getconfig(Long id) {
        return ccConfigMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update_config(SystemCcConfig ccConfig) {
        ccConfig.setOptTime(new Date());
        ccConfigMapper.updateByPrimaryKeySelective(ccConfig);
    }

    @Override
    public PageInfo<SystemCcRecord> find_record_by_page(Integer rows, Integer page, String ip, String url) {
        PageHelper.startPage(page, rows);
        if (StringUtils.isEmpty(ip)) {
            ip = null;
        }
        if (StringUtils.isEmpty(url)) {
            url = null;
        }
        List<SystemCcRecord> records = recordMapper.selectByIpUrl(ip, url);
        return new PageInfo<>(records);
    }

    @Override
    public SystemCcRecord find_by_id(Long id) {
        return recordMapper.selectByPrimaryKey(id);
    }

    @Override
    public void delete_record_by_id(Long id) {
        recordMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void save_record(SystemCcRecord record) {
        record.setCreateTime(new Date());
        record.setOptTime(new Date());
        recordMapper.insert(record);
    }

    @Override
    public void update_record(SystemCcRecord record) {
        recordMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public void delete_all_record() {
        recordMapper.deleteAll();
    }

    @Override
    public SystemCcRecord find_record_by_ip(String ip) {
        if (StringUtils.isEmpty(ip)) {
            ip = null;
        }
        List<SystemCcRecord> records = recordMapper.selectByIpUrl(ip, null);
        if (records != null && records.size() > 0) {
            return records.get(0);
        }
        return null;
    }


}
